package top.tangyh.lamp.care.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tangyh.lamp.care.converter.CatheterConverter;
import top.tangyh.lamp.care.mapper.BPipeUseRecordMapper;
import top.tangyh.lamp.care.service.BPipeUseRecordService;
import top.tangyh.basic.base.service.impl.SuperServiceImpl;
import top.tangyh.lamp.care.manager.BPipeUseRecordManager;
import top.tangyh.lamp.care.entity.BPipeUseRecord;
import top.tangyh.lamp.care.vo.query.QcQueryPageVO;
import top.tangyh.lamp.care.vo.query.PipeUseRecordQueryVO;
import top.tangyh.lamp.care.vo.result.*;
import top.tangyh.lamp.care.vo.update.ChangeYxPipeUseRecordParam;
import top.tangyh.lamp.common.utils.PDateUtils;
import top.tangyh.lamp.common.utils.YDateUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 业务实现类
 * 导管使用记录具体信息表
 * </p>
 *
 * @author zqb
 * @date 2024-07-19 15:02:24
 * @create [2024-07-19 15:02:24] [zqb] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class BPipeUseRecordServiceImpl extends SuperServiceImpl<BPipeUseRecordManager, Long, BPipeUseRecord> implements BPipeUseRecordService {


    private final BPipeUseRecordMapper bPipeUseRecordMapper;

    @Resource
    CatheterConverter catheterConverter;




    @Override
    public Map<String, Object> queryAllPipeUseRecord(PipeUseRecordQueryVO queryAllCatheterInfoParam) {
        List<PipeUseRecordVO> queryAllCatheterInfoVoList = bPipeUseRecordMapper.queryAllPipeUseRecordnfo(queryAllCatheterInfoParam);

        if (queryAllCatheterInfoVoList != null) {
            for (PipeUseRecordVO yxPipeUseRecordVO : queryAllCatheterInfoVoList) {
                this.dateSub(yxPipeUseRecordVO);
            }
        }
        List<BPipeUseRecord> singleList = bPipeUseRecordMapper.ownSelect(queryAllCatheterInfoParam);
        Map<String, Object> result = new HashMap<>(16);
        if (singleList != null && singleList.size() > 0) {
            BPipeUseRecord pipeUseRecordPO = singleList.get(0);
            PipeUseRecordVO vo = catheterConverter.queryAllYxPipeUseRecord2PipeUseRecordVO(pipeUseRecordPO);
            dateSub(vo);
            result.put("new", vo);
        } else {
            result.put("new", null);
        }
        result.put("list", queryAllCatheterInfoVoList);
        return result;
    }

    @Override
    public IPage<BPipeUseRecordResultVO> pageOfPipeUseRecord(QcQueryPageVO pipeUseRecordQcQueryVO) {
        Page<BPipeUseRecord> page = new Page<>(pipeUseRecordQcQueryVO.getPage(), pipeUseRecordQcQueryVO.getSize());

        QueryWrapper<BPipeUseRecord> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(pipeUseRecordQcQueryVO.getStartTime())) {
            queryWrapper.ge("intubation_time", pipeUseRecordQcQueryVO.getStartTime());
        }
        if (StringUtils.isNotEmpty(pipeUseRecordQcQueryVO.getEndTime())) {
            queryWrapper.le("intubation_time", pipeUseRecordQcQueryVO.getEndTime());
        }
        //部门筛选条件 等his对接后再做
        if (StringUtils.isNotEmpty(pipeUseRecordQcQueryVO.getDepartmentType())) {

        }

        queryWrapper.orderByDesc("created_time");


        page= bPipeUseRecordMapper.selectPage(page, queryWrapper);
        // 简化转换
        IPage<BPipeUseRecordResultVO> resultPage = page.convert(record -> {
//            BPipeUseRecordResultVO resultVO = new BPipeUseRecordResultVO();
//            BeanUtils.copyProperties(record, resultVO);  // 自动复制属性
            BPipeUseRecordResultVO resultVO = BeanUtil.toBean(record, BPipeUseRecordResultVO.class);
            return resultVO;
        });
        return resultPage;
    }

    @Override
    public List<StatisticsByMonth> pipeUserRecordStatisticsOfSixMonth(String startTime) {
        return bPipeUseRecordMapper.pipeUserRecordStatisticsOfSixMonth(startTime);
    }

//    @Override
//    public PageOutputDTO<BPipeUseRecordResultVO> pipeUseRecordPage(QueryPipeObsvRecorddParam query) {
//        PageHelper.startPage(query.getPage(), query.getSize());
//        Page<BPipeUseRecordResultVO> page = new Page<>(query.getPage(), query.getSize());
//
//        QueryWrapper<BPipeUseRecordResultVO> queryWrapper = new QueryWrapper<>();
//
//        if (StringUtils.isNotEmpty(query.get())) {
//            queryWrapper.like("patient_name", alarmDataQuery.getPatientName());
//        }
//        if (StringUtils.isNotEmpty(alarmDataQuery.getPatientIdent())) {
//            queryWrapper.like("patient_ident", alarmDataQuery.getPatientIdent());
//        }
//        queryWrapper.orderByDesc("created_time");
//        page= alamDataMapper.selectPage(page, queryWrapper);
//        return page;
//    }

    /**
     * 计算管道植入了多久
     * 例如植入了两天  有效期三天   则提醒剩余一天换管
     * 如果是 使用中 则根据植入日期计算  如果是换管 则依据拔管时间
     */
    private void dateSub(PipeUseRecordVO queryAllCatheterInfoVo) {
        long timeMillis = System.currentTimeMillis();   //获得系统的时间，单位为毫秒
        if ((null != queryAllCatheterInfoVo.getState())) {
            if (queryAllCatheterInfoVo.getState() == 1) {
                if (queryAllCatheterInfoVo.getImbedTime() != null) {
                    //和当前日期作比较 如果当天时间减去置入管日期 获取导管已经使用的天数
                    ZoneId zone = ZoneId.systemDefault();

                    //获取置入日期毫秒数
                    Long milliSecond = queryAllCatheterInfoVo.getImbedTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();

                    long time = (timeMillis - milliSecond) / (1000 * 24 * 60 * 60);

                    int day = (int) time + 1;
                    queryAllCatheterInfoVo.setUsedDay(day);
                    Integer inDate = queryAllCatheterInfoVo.getValidity();

                    if (null != queryAllCatheterInfoVo.getValidity()) {
                        if (day >= inDate) {
                            queryAllCatheterInfoVo.setReminderDay(0);
                        } else {
                            queryAllCatheterInfoVo.setReminderDay(inDate - day);
                        }
                    } else {
                        queryAllCatheterInfoVo.setReminderDay(0);
                    }
                }
            } else {
                if (queryAllCatheterInfoVo.getPullTime() != null) {
                    long time = (timeMillis - queryAllCatheterInfoVo.getPullTime().getTime()) / (1000 * 24 * 60 * 60);
                    int day = (int) time + 1;
                    queryAllCatheterInfoVo.setUsedDay(day);

                    Integer inDate = queryAllCatheterInfoVo.getValidity();
                    //老的逻辑
                    if (null != queryAllCatheterInfoVo.getValidity()) {
                        if (day >= inDate) {
                            queryAllCatheterInfoVo.setReminderDay(0);
                        } else {
                            queryAllCatheterInfoVo.setReminderDay(inDate - day);
                        }
                    } else {
                        queryAllCatheterInfoVo.setReminderDay(0);
                    }
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addOrUpdateYxPipeUseRecord(BPipeUseRecord pipeUseRecordPO) {
        if (pipeUseRecordPO == null) {
            return (long) 0;
        } else {

            if (pipeUseRecordPO.getId() == null) {
                bPipeUseRecordMapper.insert(pipeUseRecordPO);
                Long id = pipeUseRecordPO.getId();
                return id;
            } else {
                int flag = bPipeUseRecordMapper.updateById(pipeUseRecordPO);
                if (flag > 0) {
                    return pipeUseRecordPO.getId();
                } else {
                    return (long) -1;
                }

            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateYxPipeUseRecord(ChangeYxPipeUseRecordParam changeYxPipeUseRecordParam) {
        //1、换管将当前的更新为拔管状态
        BPipeUseRecord pipeUseRecord = this.getById(changeYxPipeUseRecordParam.getId());
        if (null != pipeUseRecord) {

            //状态(1、使用中 2、已拔管)
            pipeUseRecord.setState(2);
            pipeUseRecord.setReasonName(changeYxPipeUseRecordParam.getReasonName());
            pipeUseRecord.setReasonCode(changeYxPipeUseRecordParam.getReasonCode());
            pipeUseRecord.setPullUserId(changeYxPipeUseRecordParam.getDrawUserId());
            pipeUseRecord.setPullTime(changeYxPipeUseRecordParam.getChangeTime());
            pipeUseRecord.setChangePlaceName(changeYxPipeUseRecordParam.getChangePlaceName());
            pipeUseRecord.setUpdatedTime(LocalDateTime.now());
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            LocalDateTime ldt = LocalDateTime.parse(changeYxPipeUseRecordParam.getPullTime(), df);

            pipeUseRecord.setPullTime(changeYxPipeUseRecordParam.getPullTime());
            pipeUseRecord.setPullUserName(changeYxPipeUseRecordParam.getPullUserName());
            //换管时间和换管人   赋值拔管时间和拔管人
            pipeUseRecord.setPullTime(changeYxPipeUseRecordParam.getChangeTime());
            pipeUseRecord.setPullUserId(changeYxPipeUseRecordParam.getDrawUserId());
            int updateR = bPipeUseRecordMapper.updateById(pipeUseRecord);
            //2、新增一条使用中的管道信息
            //状态(1、使用中 2、已拔管)

            if (updateR > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteYxPipeUseRecordById(Long id) {
        if (null != id) {
            BPipeUseRecord old = this.getById(id);
            //验证是否本人的数据
//            if(null != SecurityUtil.checkRecordAuth(old.getCreateBy() ,old.getUpdateBy())){
//                throw new BadRequestException(SecurityUtil.checkRecordAuth(old.getCreateBy() ,old.getUpdateBy()));
//            }
        }
        int r = bPipeUseRecordMapper.deleteById(id);
        if (r > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<TepPipeUseRecordVO> selectTemperatureChannelByHospitalNumberAndTime(String hospitalNumber, String rkTimeStr, String cYTimeStr, String typeName) {
        Date start = YDateUtils.strToDate(rkTimeStr, YDateUtils.DATE_TIME_PATTERN);
        Date end = YDateUtils.strToDate(cYTimeStr, YDateUtils.DATE_TIME_PATTERN);

        return bPipeUseRecordMapper.selectTemperatureChannelByHospitalNumberAndTime(hospitalNumber, start, end, typeName);
    }

    @Override
    public List<BPipeUseRecord> selectValidityOfChannel(String hoverTime, String patientIdent, String hospitalNumber) {
        List<BPipeUseRecord> list = bPipeUseRecordMapper.selectValidityOfChannel(hoverTime, patientIdent, hospitalNumber);
        return list;
    }

    @Override
    public List<BPipeUseRecord> selectKeyData(String hoverTime, String patientIdent, String hospitalNumber) {
        List<BPipeUseRecord> list = bPipeUseRecordMapper.selectKeyData(hoverTime, patientIdent, hospitalNumber);
        return list;
    }

    @Override
    public int countOfUnplannedExtubation(String startTime, String endTime) {
        LambdaQueryWrapper<BPipeUseRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BPipeUseRecord::getPpTypeName,"高危导管")
                .eq(BPipeUseRecord::getPpName,"气管插管")
        .ge(BPipeUseRecord::getIntubationTime, PDateUtils.convertStringToDate(startTime))
                .le(BPipeUseRecord::getIntubationTime,   PDateUtils.convertStringToDate(endTime))
                .eq(BPipeUseRecord::getIsPlan, 1);

        // 获取符合条件的记录数量
        int count = Math.toIntExact(bPipeUseRecordMapper.selectCount(queryWrapper));
        return count;
    }

    @Override
    public int countOfUnplannedExtubationAll(String startTime, String endTime) {
        LambdaQueryWrapper<BPipeUseRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(BPipeUseRecord::getPpTypeName,"高危导管")
                .eq(BPipeUseRecord::getPpName,"气管插管")
                .ge(BPipeUseRecord::getIntubationTime,   PDateUtils.convertStringToDate(startTime))
                .le(BPipeUseRecord::getIntubationTime,  PDateUtils.convertStringToDate(endTime));

        // 获取符合条件的记录数量
        int count = Math.toIntExact(bPipeUseRecordMapper.selectCount(queryWrapper));
        return count;
    }

}


